import 'package:flutter/material.dart';

class Product {
  const Product({this.name});
  final String name;
}

typedef void CartChangeCallback(Product product, bool inCart);

// 订单item
class ShoppingItem extends StatelessWidget {
  ShoppingItem({this.product, this.inCart, this.onCartChanged});
  final Product product;
  final bool inCart;
  final CartChangeCallback onCartChanged;

  Color _getColor(BuildContext context) {
    return inCart ? Colors.black38 : Theme.of(context).primaryColor;
  }

  TextStyle _getTextStyle(BuildContext context) {
    if (!inCart) return null;

    return new TextStyle(
      color: Colors.black38,
      decoration: TextDecoration.lineThrough,
    );
  }

  @override
  Widget build(BuildContext context) {
    return new ListTile(
        onTap: () {
          onCartChanged(product, !inCart);
        },
        leading: new CircleAvatar(
          backgroundColor: _getColor(context),
          child: new Text(product.name[0]),
        ),
        title: new Text(product.name, style: _getTextStyle(context)));
  }
}

// 订单list
class ShoppingList extends StatefulWidget {
  ShoppingList({Key key, this.products}) : super(key: key);

  final List<Product> products;

  @override
  State<StatefulWidget> createState() {
    return new ShoppingListState();
  }
}

class ShoppingListState extends State<ShoppingList> {
  Set<Product> _shoppingCart = new Set<Product>();

  void _handleCartChanged(Product product, bool isCart) {
    setState(() {
      if (isCart)
        _shoppingCart.add(product);
      else
        _shoppingCart.remove(product);
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("Shopping List"),
      ),
      body: new ListView(
          padding: new EdgeInsets.symmetric(vertical: 18.0),
          children: widget.products.map((Product product) {
            return new ShoppingItem(
              product: product,
              inCart: _shoppingCart.contains(product),
              onCartChanged: _handleCartChanged,
            );
          }).toList()),
    );
  }
}
